"""
连接阿里云oss

"""
# 连接aliOss
import gzip
import os

import oss2

from dotenv import load_dotenv

load_dotenv('env.ini', encoding='utf-8')


class AliOss(object):
    def __init__(self):
        self.auth = oss2.Auth(os.getenv('access_key_id'), os.getenv('access_key_secret'))
        bucket_name = os.getenv('bucket_name') or 'TeSuchSDNTraffic'
        self.bucket = oss2.Bucket(self.auth, 'http://oss-cn-beijing.aliyuncs.com', bucket_name)

    def put_object(self, k, v):
        headers = dict()
        headers['content-type'] = 'application/json'
        headers['content-encoding'] = 'gzip'
        try:
            result = self.bucket.put_object(k, gzip.compress(bytes(v, 'utf-8')), headers=headers)
            return True if result.status == 200 else False
        except Exception as e:
            print(e)
            return False

    def get_object(self, k):
        headers = dict()
        headers['accept-encoding'] = 'gzip'
        try:
            result = self.bucket.get_object(k, headers=headers)
            return result.read().decode('utf8')
        except Exception as e:
            print(e)
            return ''

    def del_object(self, k):
        try:
            result = self.bucket.delete_object_versions([k])
            return result.delete_marker
        except Exception as e:
            print(e)
            return False
